package com.leyou.cart.interceptor;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.cart.config.JwtProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties jwtProperties;

    // 将用户信息存放在线程变量(线程域)中
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取cookie中的token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());

        // 判断token是否存在
        if (StringUtils.isBlank(token)){
            // 查询购物车中对应skus不拦截
            String requestURI = request.getRequestURI();

            if(StringUtils.startsWith(requestURI,"/selectedSkus")){
                return true;
            }

            // 为空，未登录，返回401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        // 解析token，获取其中的用户信息
        try {
            // 解析成功，证明已经登录
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            // 放入线程域
            THREAD_LOCAL.set(userInfo);
            // 放行
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            // 抛出异常，证明未登录,返回401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            // 拦截
            return false;
        }


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 释放THREAD_LOCAL线程域中存储的用户信息(必须手动释放，因为是线程池，如果不释放，回收后会再次使用，绝对不允许)
        THREAD_LOCAL.remove();
    }

    // 提供获取线程域中用户信息的静态方法
    public static UserInfo getUserInfoFromThread(){
        return THREAD_LOCAL.get();
    }
}
